package com.tomowork.dao.impl;

import com.tomowork.dao.IEmpDAO;

import com.tomowork.entity.Emp;
import org.springframework.stereotype.Repository;


import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import java.util.Iterator;
import java.util.List;


@Repository
public class EmpDAOImpl implements IEmpDAO{
    @PersistenceContext //获取和当前事务相关的entityManager
    private EntityManager entityManager;


    @Override
    public void doCreate(Emp emp) {
        entityManager.merge(emp);
    }

    @Override
    public boolean doUpdate(Emp emp) {
        if(emp==null){
            return false ;
        }
        String jqql = "update Emp e  SET e.ename=:ename,e.dept.deptno=:deptno where e.empno = :empno";
        Query query =entityManager.createQuery(jqql);
        query.setParameter("ename",emp.getEname())
                .setParameter("deptno",emp.getDept().getDeptno())
                .setParameter("empno",emp.getEmpno()) ;
        return query.executeUpdate()>0;
    }

    @Override
    public boolean doRemove(Integer empno) {
        String jqql = "delete from Emp e where e.empno =?" ;
        Query query = entityManager.createQuery(jqql);
        return query.setParameter(0,empno).executeUpdate()>0;
    }

    @Override
    public Emp findByEmpno(Integer empno) {
        String hql = "from Emp e where e.empno = ?" ;
        TypedQuery<Emp> query = entityManager.createQuery(hql, Emp.class);
        query.setParameter(0,empno) ;
        Emp emp = query.getSingleResult();

        return emp;
    }

    @Override
    public List<Emp> findAll(int pageNum,int pageSize) {
        String hql = "from Emp" ;
        Query query = entityManager.createQuery(hql);
        query.setFirstResult(pageNum) ;
        query.setMaxResults(pageSize) ;
        List<Emp> allEmps = query.getResultList();
        return allEmps;
    }

    @Override
    public void BatchSave(List<Emp> emps) {
        Iterator<Emp> iter = emps.iterator() ;
        while(iter.hasNext()){
            entityManager.persist(iter.next());
        }

    }

    @Override
    public int getAllCount() {
        String jpql = "select count(1) from Emp" ;
        Query query = entityManager.createQuery(jpql);
        long y = (long)query.getSingleResult();
        int x = (int)y ;
        return x;
    }

}
